import React, {FC, useMemo} from 'react';
import {ItemGraph} from "./DrawScroll";
import {Arrow, Group, Rect, Text} from "react-konva";

export enum ArrowEnum {
  left,
  right,
}

export interface EdgeProps {
  startNode: ItemGraph
  endNode: ItemGraph
  text1: string
  arrow: ArrowEnum
  index: number
  period: number
  isHigh: boolean
  onClick: (index: number) => void
  fontSize: number
}

const Edge: FC<EdgeProps> = (props) => {
  const {endNode, startNode, text1, arrow, period, isHigh, index, onClick,fontSize} = props;
  const dx = endNode.x - startNode.x;
  const dy = endNode.y - startNode.y;
  let angle = Math.atan2(-dy, dx);

  const radius = 1;

  const timeStr = useMemo(() => {
    if (period === 0) {
      return '0 ms';
    }
    if (period > 1) {
      return period.toFixed(2) + ' s';
    }
    if (period * 1000 > 1) {
      return (period * 1000).toFixed(2) + ' ms';
    }
    return (period * 1000000).toFixed(2) + ' μs';

  }, [period]);

  const arrowStart = {
    x: startNode.x + -radius * Math.cos(angle + Math.PI),
    y: startNode.y + radius * Math.sin(angle + Math.PI)
  };

  const arrowEnd = {
    x: endNode.x + -radius * Math.cos(angle),
    y: endNode.y + radius * Math.sin(angle)
  };

  const arrowMiddle = {
    x: (arrowStart.x + arrowEnd.x) / 2,
    y: (arrowStart.y + arrowEnd.y) / 2
  };


  let text1Width = arrow === ArrowEnum.right ? endNode.x - startNode.x : startNode.x - endNode.x;
  let text1X = arrow === ArrowEnum.right ? startNode.x + 3 : endNode.x;
  let color = useMemo(() => {
    return isHigh ? 'blue' : 'black'
  }, [isHigh])
  return (
    <Group onClick={() => {
      onClick(index)
    }}>
      <Rect
        x={arrow === ArrowEnum.right ? startNode.x : endNode.x}
        y={(arrow === ArrowEnum.right ? startNode.y : endNode.y) - 20}
        width={arrow === ArrowEnum.right ? endNode.x - startNode.x : startNode.x - endNode.x}
        height={40}
      />
      <Arrow
        points={[
          arrowStart.x,
          arrowStart.y,
          arrowMiddle.x,
          arrowMiddle.y,
          arrowEnd.x,
          arrowEnd.y
        ]}
        stroke={color}
        fill={color}
        strokeWidth={1}
        pointerWidth={4}
      />
      <Text
        fill={color}
        x={text1X}
        y={startNode.y - fontSize}
        width={text1Width}
        height={fontSize}
        fontSize={fontSize}
        text={text1}
        align={arrow === ArrowEnum.right ? 'left' : 'right'}
        verticalAlign={'middle'}

      />
      <Text
        fill={color}
        x={text1X}
        y={startNode.y + fontSize / 2}
        width={text1Width}
        height={fontSize}
        fontSize={fontSize}
        text={timeStr}
        align={arrow === ArrowEnum.right ? 'left' : 'right'}
        verticalAlign={'middle'}

      />
    </Group>
  );
};

export default Edge;
